package conf

import (
	"fmt"
	"sync"
	_ "vblog/middleware"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

type app struct {
	Host   string `json:"host,omitempty" yaml:"host"`
	Port   int    `json:"port,omitempty" yaml:"port"`
	Domain string `json:"domain,omitempty"`

	server *gin.Engine
	// type IRouter interface {
	// IRoutes
	// Group(string, ...HandlerFunc) *RouterGroup
	// }
	root gin.IRouter
	lock sync.Mutex
}

func App() *app {
	return &app{
		Host:   "127.0.0.1",
		Port:   9000,
		Domain: "http://127.0.0.1",
	}
}

func (a *app) Address() string {
	return fmt.Sprintf("%s:%d", a.Host, a.Port)
}

// Gin Engine
func (a *app) GinServer() *gin.Engine {
	a.lock.Lock()
	defer a.lock.Unlock()
	if a.server == nil {
		a.server = gin.Default()
	}
	a.server.Use(cors.Default())
	// a.server.Use(middleware.CORS)

	return a.server
}

// 返回 engine - rootRouter - group router
func (a *app) RootRouter() gin.IRouter {
	// Gin Irouter 是个interface

	v := "v1"
	if a.root == nil {
		a.root = a.GinServer().Group("vblog").Group("api").Group(v)

	}
	return a.root
}

// 启动gin server
func (a *app) Start() error {
	return a.GinServer().Run(a.Address())
}
